package com.android.xk.mask.guard

import android.app.ActivityManager
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.TrafficStats
import android.os.IBinder
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import android.widget.Toast
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.android.xk.mask.App
import com.android.xk.mask.IGuardInterface
import com.android.xk.mask.client.SocketClient
import com.android.xk.mask.getDiskRate
import com.android.xk.mask.getProcessCpuRate
import com.android.xk.mask.model.Message
import com.android.xk.mask.model.SystemMonitor
import com.apkfuns.logutils.LogUtils
import java.io.BufferedReader
import java.io.FileReader


class LocalService : Service(), AMapLocationListener {

    private var mBinder: GuardBinder? = null

    private val mLocationClient by lazy {
        AMapLocationClient(applicationContext).apply {
            setLocationListener(this@LocalService)
        }
    }

    private val mLocationOption by lazy {
        AMapLocationClientOption().apply {
            locationMode = AMapLocationClientOption.AMapLocationMode.Battery_Saving
            interval = 30000
        }
    }

    private val tm: TelephonyManager by lazy {
        getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    }

    private var sequence = 1
    var mRSSI = 0

    inner class MyPhoneStateListener : PhoneStateListener() {
        override fun onSignalStrengthsChanged(signalStrength: SignalStrength?) {
            mRSSI = signalStrength?.level ?: 0
            super.onSignalStrengthsChanged(signalStrength)
        }
    }

    override fun onBind(intent: Intent): IBinder {
        mBinder = GuardBinder()
        return mBinder as GuardBinder
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        return START_STICKY
    }

    override fun onCreate() {
        super.onCreate()
        LogUtils.e("LocalService 启动")
        mLocationClient.setLocationOption(mLocationOption)
        mLocationClient.stopLocation()
        mLocationClient.startLocation()
        tm.listen(MyPhoneStateListener(), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)
    }

    override fun onLocationChanged(location: AMapLocation?) {
        location?.let {
            LogUtils.i("经纬度：${it.longitude}  ${it.latitude}")
            if (App.deviceId == null) return
            val msg = Message().apply {
                msgLen = 88
                msgId = 0x0F000003
                deviceId = App.deviceId!!
                sequence = this@LocalService.sequence++
            }

            msg.userData = SystemMonitor().apply {
                rssi = this@LocalService.mRSSI
                cpuRate = getProcessCpuRate()
                memRate = getUsedPercentValue()
                hddRate = getDiskRate()
                upRate = (TrafficStats.getTotalTxBytes() / 1024).toInt()
                downRate = (TrafficStats.getTotalRxBytes() / 1024).toInt()
                latitude = it.latitude.toString()
                longitude = it.longitude.toString()
            }
            LogUtils.e("发送运行数据 ${msg.userData.toString()}")
            SocketClient.send(msg)
        }
    }

    private fun getAvailableMemory(): Long {
        val mi = ActivityManager.MemoryInfo()
        val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        am.getMemoryInfo(mi)
        return mi.availMem
    }

    private fun getUsedPercentValue(): Int {
        val dir = "/proc/meminfo"
        var percent = 0
        try {
            val fr = FileReader(dir)
            val br = BufferedReader(fr, 2048)
            val memoryLine = br.readLine()
            val subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"))
            br.close()
            val totalMemorySize =
                subMemoryLine.replace("\\D+".toRegex(), "").toInt().toLong()
            val availableSize = getAvailableMemory() / 1024
            percent = ((totalMemorySize - availableSize) / totalMemorySize.toFloat() * 100).toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return percent
    }


//    private static long getAvailableMemory(Context context) {
//        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
//        getActivityManager(context).getMemoryInfo(mi);
//        return mi.availMem;
//    }
}
